### PACKAGE PREAMBLE ###

# Create a vector of package names
packages <- c("dplyr", "ggplot2", "tidyr", "tidyverse", "data.table", "readxl", "foreign", "devtools", "fixest", "sandwich", "modelsummary", "kableExtra")

installed_packages <- packages %in% rownames(installed.packages())
if (any(installed_packages == FALSE)) {
  install.packages(packages[!installed_packages])
}

# Packages loading
invisible(lapply(packages, library, character.only = TRUE))
rm(packages, installed_packages)

options(modelsummary_format_numeric_latex = "plain")
f <- function(x) format(x, digits = 3, nsmall = 2, scientific = FALSE)

getwd()
setwd(dir = "/Users/jmc4qg/The Lab Dropbox/Jonathan Colmer/ShotSpotter_env/Journal_submissions/ReStat/Replication Folder/")
mydata <- read.dta("Analysis Data/NIBRS_analysis.dta")

# Panel A: Home

T1_home <- feols(homicide_at_home_pc~ tMean + prec , data=mydata)
summary(T1_home, cluster="fips")
T2_home <- feols(homicide_at_home_pc~ tMean + prec | sample_month + week + dow, data=mydata)
summary(T2_home, cluster="fips")
T3_home <- feols(homicide_at_home_pc~ tMean + prec | state_sample_month + week + dow, data=mydata)
summary(T3_home, cluster="fips")
T4_home <- feols(homicide_at_home_pc~ tMean + prec | ori_sample_month + week + dow, data=mydata)
summary(T4_home, cluster="fips")

models <- list(T1_home, T2_home, T3_home, T4_home)
modelsummary(models, vcov = ~fips,  output = "Figures and Tables/Table_C3/Table_C3_Panel_A.tex", fmt = f, stars = c('*' = 0.1, '**' = 0.05, '***' = 0.01))

# Panel B: Outside

T1_outside <- feols(homicide_outside_pc~ tMean + prec , data=mydata)
summary(T1_outside)
T2_outside <- feols(homicide_outside_pc~ tMean + prec | sample_month + week + dow, data=mydata)
summary(T2_outside, cluster="fips")
T3_outside <- feols(homicide_outside_pc~ tMean + prec | state_sample_month + week + dow, data=mydata)
summary(T3_outside, cluster="fips")
T4_outside <- feols(homicide_outside_pc~ tMean + prec | ori_sample_month + week + dow, data=mydata)
summary(T4_outside, cluster="fips")

models <- list(T1_outside, T2_outside, T3_outside, T4_outside)
modelsummary(models, vcov = ~fips,  output = "Figures and Tables/Table_C3/Table_C3_Panel_B.tex", fmt = f, stars = c('*' = 0.1, '**' = 0.05, '***' = 0.01))

# Panel C: Other

T1_other <- feols(homicide_other_pc~ tMean + prec , data=mydata)
summary(T1_other)
T2_other <- feols(homicide_other_pc~ tMean + prec | sample_month + week + dow, data=mydata)
summary(T2_other, cluster="fips")
T3_other <- feols(homicide_other_pc~ tMean + prec | state_sample_month + week + dow, data=mydata)
summary(T3_other, cluster="fips")
T4_other <- feols(homicide_other_pc~ tMean + prec | ori_sample_month + week + dow, data=mydata)
summary(T4_other, cluster="fips")

models <- list(T1_other, T2_other, T3_other, T4_other)
modelsummary(models, vcov = ~fips,  output = "Figures and Tables/Table_C3/Table_C3_Panel_C.tex", fmt = f, stars = c('*' = 0.1, '**' = 0.05, '***' = 0.01))
